// 使用forEach进行读取文件，会因为读取过快而导致报错
// DOMException: Failed to execute 'readAsArrayBuffer' on 'FileReader': The object is already busy reading Blobs.
// DomeException:未能在“FileReader”上执行“readAsArrayBuffer”：对象已在忙于读取Blob。
self.importScripts("spark-md5.min.js");

onmessage = function (e) {
  const { chunks } = e.data;
  const fileReader = new FileReader(); 
  const len = chunks.length;
  const spark = new SparkMD5.ArrayBuffer();
 

  fileReader.onload = (e) => {
    spark.append(e.target.result);    
  }; 

  chunks.forEach((chunk, index) => { 
    fileReader.readAsArrayBuffer(chunk.file);
    
    this.postMessage({
      progress: Number(((index / len) * 100).toFixed(2)),
    });
  })

  // 最终值
  this.postMessage({
    progress: 100,
    hash: spark.end(),
  });
};
